package com.sy.simpleegg.ui.horizontalrecyclerview.layoutmanager

import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.util.DisplayMetrics
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView

class LoopLinearLayoutManager : LinearLayoutManager {
    private var speedPerPixel = 10f //数值越大越慢 0.001
    private var context: Context? = null

    constructor(context: Context?) : super(context) {
        this.context = context
    }

    constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(
        context,
        orientation,
        reverseLayout
    )

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes)

    fun setSpeedPerPixel(speedPerPixel: Float) {
        this.speedPerPixel = speedPerPixel
    }

    override fun canScrollVertically(): Boolean {
//        return super.canScrollVertically();
        return false
    }

    override fun smoothScrollToPosition(
        recyclerView: RecyclerView,
        state: RecyclerView.State,
        position: Int
    ) {
//        super.smoothScrollToPosition(recyclerView, state, position);
        val smoothScroller: RecyclerView.SmoothScroller =
            LoopSmoothScroolController(recyclerView.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private inner class LoopSmoothScroolController(context: Context?) :
        LinearSmoothScroller(context) {
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
//            return super.computeScrollVectorForPosition(targetPosition);
            return this@LoopLinearLayoutManager.computeScrollVectorForPosition(targetPosition)
        }

        override fun calculateDtToFit(
            viewStart: Int,
            viewEnd: Int,
            boxStart: Int,
            boxEnd: Int,
            snapPreference: Int
        ): Int {
//            return super.calculateDtToFit(viewStart, viewEnd, boxStart, boxEnd, snapPreference);
            return boxStart + (boxEnd - boxStart) / 2 - (viewStart + (viewEnd - viewStart) / 2)
        }

        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
//            return super.calculateSpeedPerPixel(displayMetrics);
            return speedPerPixel
        }

        override fun getHorizontalSnapPreference(): Int {
//            return super.getHorizontalSnapPreference();
            return SNAP_TO_START
        }
    }

    fun setSpeedSlow() {
        speedPerPixel = context!!.resources.displayMetrics.density * 3
    }

    fun setSpeedFast() {
        speedPerPixel = context!!.resources.displayMetrics.density * 0.03f
    }
}
